package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.redis.CacheHelper;
import com.atguigu.gmall.activity.service.ActivityService;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.rabbit.constant.MqConst;
import com.atguigu.gmall.rabbit.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: 李旭
 * @Time: 11:31
 * @Description:
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillApiController {


    @Autowired
    private ActivityService activityService;
    @Autowired
    private RabbitService rabbitService;

    public static final String salt = "qazxsw";

    //获取抢购码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {

        String userId = AuthContextHolder.getUserId(request);

        SeckillGoods seckillGoods = activityService.findBySkuId(skuId);
        //1:活动时间
        Date startTime = seckillGoods.getStartTime();
        Date endTime = seckillGoods.getEndTime();
        Date curTime = Calendar.getInstance().getTime();

        if (DateUtil.dateCompare(startTime, curTime) && !DateUtil.dateCompare(endTime, curTime)) {
            //抢购码
            String encrypt = MD5.encrypt(salt + userId);
            return Result.ok(encrypt);
        } else {
            return Result.fail().message("不在活动时间范围内");
        }
        //2:审核通过
        //3:剩余库存大于0
    }

    //开始秒杀
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, String skuIdStr, HttpServletRequest request) {

        String userId = AuthContextHolder.getUserId(request);
//        1、校验抢购码
        String encrypt = MD5.encrypt(salt + userId);
        if (!encrypt.equals(skuIdStr)) {
            return Result.fail().message("抢购码失败");
        }
//        2、校验状态位
        Object status = CacheHelper.get(skuId.toString());
        if (!"1".equals(status)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
//        3、发消息
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);
        userRecode.setSkuId(skuId);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                MqConst.ROUTING_SECKILL_USER,userRecode);
        return Result.ok();
    }
    //开始检查
//        Redis
//    1、商品信息
//    2、库存信息
//    3、用户来过没
//    4、抢购资格
//    5、用户下的单
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
//        1、检验5
        Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
        if(null != o1){
            return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);
        }
//        2、检查4
        Object o2 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
        if(null != o2){
            return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);
        }
//        3、检查3&状态位
        Object o3 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId);
        if(null == o3){
            //用户没有来过
            Object o4 = CacheHelper.get(skuId.toString());
            if("1".equals(o4)){
                return Result.build(null,ResultCodeEnum.SECKILL_RUN);
            }
        }
        //没有抢到
        return Result.build(null,ResultCodeEnum.SECKILL_FAIL);
    }

    @Autowired
    private RedisTemplate redisTemplate;

}
